<template>
  <div class="app-container">
    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item name="1">
        <template slot="title">
          <MmvTitle title="订单信息"></MmvTitle>
        </template>
        <el-form label-width="120px">
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="订单编号:">{{shortBasic.orderNo || '--'}}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称:">{{shortBasic.memberName || '--'}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预约取车时间:">{{shortBasic.rentalStartTime || '--'}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预约还车时间:">{{shortBasic.rentalEndTime || '--'}}</el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="预约租期:">{{shortBasic.leaseDays || '--'}}天</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际取车时间:">{{shortBasic.actualStartTime || '--'}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际还车时间:">{{shortBasic.actualEndTime || '--'}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际租期:">{{detail.actualLeaseDays || '--'}}天</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="汽车租赁押金:">{{shortBasic.deposit || '--'}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="押金支付类型:">{{shortBasic.depositPayType|depositPayType}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付方式:">{{shortBasic.depositPayWay|depositPayWay}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抵扣金额:"><strong>{{depositDeduct || '--'}}</strong></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="补缴金额:"><strong>{{payTheCostSum || '--'}}</strong></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="应退金额:"><strong>{{depositRefund || '--'}}</strong></el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item name="2"><template slot="title">
          <MmvTitle title="预付费"></MmvTitle>
        </template>
        <el-table :data="detail.chargingItems" :span-method="objectSpanMethod" border
          style="width: 100%; margin-top: 20px">
          <el-table-column label="费用名称" align="center" prop="name" />
          <el-table-column label="收费项目名称" align="center" prop="chargeProjectName" />
          <el-table-column label="数量" align="center" prop="number" />
          <el-table-column label="收费类型" align="center" prop="chargeItemsType">
            <template slot-scope="{row}">
              <dict-tag :options="dict.type.charge_type" :value="row.chargeItemsType" />
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="unitPrice" />
          <el-table-column label="收费金额" align="center" prop="chargeMoney" />
          <el-table-column label="支付方式" align="center" prop="payType">
            <template slot-scope="{row}">
              <dict-tag :options="dict.type.sys_pay_type" :value="row.payType" />
            </template>
          </el-table-column>
        </el-table>

      </el-collapse-item>
    </el-collapse>
    <MmvTitle title="押金扣款明细">
      <div slot="btn">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['order:settlement:add']">新增</el-button>
      </div>
    </MmvTitle>


    <el-table v-loading="loading" :data="detail.settlementList" border show-summary>
      <el-table-column label="扣款原因" align="center" prop="deductionsFor" />
      <el-table-column label="扣款金额" align="center" prop="deductionsAmount" />
      <el-table-column label="来源" prop="source">
        <template slot-scope="{row}">
          {{ {1:'手动添加', 2:'还车验车'}[Number(row.source)] }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['order:settlement:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['order:settlement:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改押金结算对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body destroy-on-close>
      <MmvAdd ref="MmvAdd" :id="form.id" :type="1" v-if="open"></MmvAdd>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitBtnLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
  import {
    depositRefundDetail
  } from '@/api/luxuryOrder/index';
  import {
    overDepositSettlement,
    depositRefund,
    IllegalRefund,
    listSettlement,
    getSettlement,
    delSettlement,
    addSettlement,
    updateSettlement,
    exportSettlement
  } from "@/api/order/settlement";
  import MmvTitle from '@/components/MmvUI/MmvTitle.vue';
  import MmvAdd from './settlement-add.vue';
  export default {
    components: {
      MmvTitle,
      MmvAdd
    },
    dicts: ['sys_pay_type', 'order_payStatus', 'charge_type'],
    props: ['orderNo'],
    filters: {
      depositPayType(val) {
        return {
          1: '线上',
          2: '线下',
          3: '微信支付分',
        } [Number(val)] || '--';
      },
      depositPayWay(val) {
        return {
          1: '微信',
          2: '支付宝',
          3: '信用卡',
          4: '现金',
          5: '微信支付分',
        } [Number(val)] || '--';
      },
    },
    data() {
      return {
        submitBtnLoading: false,
        // orderNo: '13259c14b6f1483b9c1425e7413afad3',
        activeNames: ['1','2'],
        detail: {},
        shortBasic: {
          orderNo: '',
          deposit: ''
        },
        loading: true,
        btnLoadIng: false,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        // 表单校验
        rules: {}

      }
    },
    computed: {
      depositDeduct() {
        let sum=0;
        for(let item of this.detail.settlementList){
          sum+=Number(item.deductionsAmount);
        }
        return sum<=this.shortBasic.deposit?sum:this.shortBasic.deposit
      },
      payTheCostSum() {
        let sum=0;
        for(let item of this.detail.settlementList){
          sum+=Number(item.deductionsAmount);
        }
        return sum<=this.shortBasic.deposit?0:sum-this.shortBasic.deposit
      },

      depositRefund() {
        let sum=0;
        for(let item of this.detail.settlementList){
          sum+=Number(item.deductionsAmount);
        }
        return sum<=this.shortBasic.deposit?this.shortBasic.deposit-sum:0
      },
    },
    mounted() {
      this.doDepositRefundDetail();
    },
    methods: {
      doDepositRefundDetail() {
        depositRefundDetail(this.orderNo).then(response => {
          this.detail = response.data || {};
          this.shortBasic = response.data.shortBasic || {};
          console.log(response.data)
          console.log(response.data.shortBasic)
          this.loading = false
        });
      },

      confirmReceipt(row) {
        this.btnLoadIng = true;
        confirmReceipt(row.id).then(response => {
          this.doDepositRefundDetail();
          this.btnLoadIng = false
        });
      },

      confirmReceiptAll() {
        this.btnLoadIng = true;
        confirmReceiptAll(this.orderNo).then(response => {
          this.doDepositRefundDetail();
          this.btnLoadIng = false
        });
      },
      // /** 确认押金结算退款 */
      // doDepositRefund() {
      //   this.$modal.confirm('是否确认押金结算退款？').then(() => {
      //     this.btnLoadIng = true;
      //     depositRefund(this.orderNo).then(response => {
      //       this.$message.success(response.msg)
      //       this.doDepositRefundDetail();
      //       this.btnLoadIng = false
      //     });
      //   })
      // }, // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          orderNo: this.orderNo,
          type: this.type,
          deductionsFor: null,
          deductionsAmount: null,
          deductionsWay: null,
          illegalRecordId: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          tenantId: null,
          cheSunImage: [], // 车损照片
          maintainImage: [], // 维修单据
          illegalImage: [], // 违章单据
        };
        this.resetForm("form");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getSettlement(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.submitBtnLoading = true;
        setTimeout(()=>{
          this.submitBtnLoading = false;
        },2e3)
        const form = this.$refs?.MmvAdd?.emitData() || {};
        const valid = this.$refs?.MmvAdd?.validForm() || false;
        form.orderNo = this.orderNo
        if(valid){
          if (form.id != null) {
            updateSettlement(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.doDepositRefundDetail();
            });
          } else {
            addSettlement(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.doDepositRefundDetail();
            });
          }
        }

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除数据项？').then(function() {
          return delSettlement(ids);
        }).then(() => {
          this.doDepositRefundDetail();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          if (index === 1) {
            const values = data.map(item => Number(item[column.property]));
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += ' 元';
          }
        });

        return sums;
      },
      objectSpanMethod({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        let rowspan = this.detail.chargingItems.length - 2;
        if (columnIndex === 0 || columnIndex > 5) {
          if (rowIndex === 0 && rowIndex < rowspan) {
            return {
              rowspan: rowspan,
              colspan: 1
            };
          } else if (rowIndex > 0 && rowIndex < rowspan) {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }

        if (columnIndex > 5 && rowIndex >= rowspan) {
          if (rowIndex === rowspan) {
            return {
              rowspan: 2,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
        if (rowIndex >= rowspan) {
          if (columnIndex === 0) {
            return [1, 2];
          } else if (columnIndex === 1) {
            return [0, 0];
          } else if (columnIndex === 5) {
            return [1, 4];
          } else if (columnIndex < 5) {
            return [0, 0];
          }
        }
      }
    },

  }
</script>

<style scoped="scoped">
  .mmv-title {
    margin: 0 !important;
    border-bottom: none !important;
  }

  .el-form-item {
      margin-bottom: 0px !important;
  }

  .el-table--medium .el-table__cell {
      padding: 3px !important;
  }
</style>
